#!/usr/bin/env python
#coding=utf-8
import random

from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest
client = AcsClient('LTAIxHzRHsM39Ejh', 'Access_Key', 'default')

# 请求的数据
request = CommonRequest()
request.set_accept_format('json')
request.set_domain('dysmsapi.aliyuncs.com')
request.set_method('POST')
request.set_protocol_type('https')  # https | http
request.set_version('2017-05-25')
request.set_action_name('SendSms')


# 注册调用方法
def send_sms(mobile, sms_code):
    request.add_query_param('PhoneNumbers', mobile)  # 配置手机号(注册&登陆的手机号)
    request.add_query_param('SignName', "ZERO")  # 配置签名
    request.add_query_param('TemplateCode', "SMS_168305980")  # 发送短信的模板配置
    request.add_query_param('TemplateParam', '{"code":"%s"}' % sms_code)  # 模板的临时变量(验证码)

    response = client.do_action(request)
    # python2:  print(response)
    print(str(response, encoding='utf-8'))
    print('--------------444------------------')
    print('生成的短信验证码', sms_code)


if __name__ == '__main__':
    send_sms('19805296308', '123456')


# # 视图函数(添加到对应的视图&蓝图标记)
# @蓝图名.route('/smscode', methods=['POST'])
# def send_sms_code():
#     """
#     发送短信验证码:
#     1. 接收参数(`手机号mobile`, `图片验证码image_code`, `图片验证码标识image_code_id`)并进行参数校验
#     2. 对比图片验证码文本，如果一致
#     3. 使用云通讯给`手机号mobile`发送短信验证码
#     4. 返回应答，发送短信成功
#     """
#     # 取浏览器传递的json数据
#     mobile = request.json.get('mobile')
#
#     if not mobile:
#         ret = {
#             "errno": 2003,
#             "errmsg": "缺少参数"
#         }
#         return jsonify(ret)
#
#     if not re.match(r'^1[3-9]\d{9}$', mobile):
#         ret = {
#             "errno": 2004,
#             "errmsg": "手机号码格式不正确"
#         }
#         return jsonify(ret)
#
#     # 4. 使用云通讯给`手机号mobile`发送短信验证码
#     # 4.1 随机生成一个6位数字
#     sms_code = str(random.randint(100000, 999999))
#
#     # 调用阿里云接口，发送短信
#     send_sms(mobile, sms_code)
#
#     # 将发送的短信验证码 存储到session中
#     session["sms_code"] = sms_code
#
#     ret = {
#         "errno": 2007,
#         "errmsg": "发送短信成功"
#     }
#     return jsonify(ret)
#



